package com.woniu40.petai_user.service;

import com.woniu40.petai_user.entity.Cart;
import com.woniu40.petai_user.entity.Goods;
import com.woniu40.petai_user.entity.Order;
import com.woniu40.petai_user.entity.OrderItem;
import com.woniu40.petai_user.mapper.CartMapper;
import com.woniu40.petai_user.mapper.GoodsMapper;
import com.woniu40.petai_user.mapper.OrderItemMapper;
import com.woniu40.petai_user.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderItemService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CartMapper cartMapper;

    @Transactional
    public Order addOrderItem(List<Integer> cartIds, Integer addressId,Integer userId){
        //判断库存
        for (Integer cartId : cartIds) {
            Cart cart = cartMapper.selectCartById(cartId);
            Goods goods = goodsMapper.selectByPrimaryKey(cart.getGoodsId());
            if (goods.getStoreCount()<1){
                throw new RuntimeException(goods.getGoodsName()+"---库存不足！！！");
            }
        }

        //插入付款记录到t_order
        List<Cart> cartList = cartMapper.selectCartByIds(cartIds);

        String orderNum = UUID.randomUUID().toString().replace("-", "");
        BigDecimal totalPrice = new BigDecimal("0.00");
        //计算付款总金额
        for (Cart cart : cartList) {
            totalPrice=totalPrice.add(cart.getAllPrice());
        }

        Order order = new Order();
        order.setOrderNum(orderNum);
        order.setCreateTime(new Date());
        order.setTotalPrice(totalPrice);
        order.setUserId(userId);
        order.setAddressId(addressId);
        order.setOrderStatus(1);

        orderMapper.insert(order);


        //批量插入订单数据
        List<OrderItem> orderItemList = cartList.stream().map(cart -> {
            OrderItem orderItem = new OrderItem(null, cart.getGoodsId(), cart.getBuyCount(),cart.getAllPrice(),
                    cart.getColorId(),cart.getTasteId(),cart.getSizeId(),order.getOrderId(),userId,cart.getCartId());

            return orderItem;
        }).collect(Collectors.toList());

        orderItemMapper.insertBatch(orderItemList);
        System.out.println(orderItemList);//测试是否成功

        return order;
    }

    public List<OrderItem> findByOrderId(Integer orderId){
        List<OrderItem> orderItemList = orderItemMapper.selectByOrderId(orderId);
        return orderItemList;
    }
}
